<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;

class Log extends Controller
{
    public function login()
    {
        return view('index/login',[
            'title'=>'Login'
        ]);
    }

    public function doLog(Request $request)
    {
        $data = $request->post();

        $data['userpass'] = md5($data['userpass']);
        $res = Db::name('admin_user')
            ->where('userpass','=',$data['userpass'])
            ->where('username','eq',$data['username'])->find();

        if(empty($res)){$this->error('登录失败');}
        // 存session
        Session::set('admin_user',$res);


        //根据用户id获取对应的节点信息
        // $sql = "select n.mname,n.aname from lamp_user u join lamp_user_role ur on u.id=ur.uid join lamp_role_node rn on ur.rid=rn.rid join lamp_node n on rn.nid=n.id where u.id={$res['id']}";
        // $list = db()->query($sql);

        $list = db('node')->field('mname,aname')->where('id in'.
            db('role_node')->field('nid')->where("rid in ".db('user_role')->field('rid')->where(array('uid'=>array('eq',$res['id'])))->buildSql())->buildSql())->select();

        //控制器名转换为大写
        foreach ($list as $key => $val) {
            $list[$key]['mname'] = ucfirst($val['mname']);
        }

        $nodelist = array();
        $nodelist['Index'] = array('index');
        //遍历重新拼装
        foreach($list as $v){
            $nodelist[$v['mname']][] = $v['aname'];
            //把修改和执行修改 添加和执行添加 拼装到一起
            if($v['aname']=="edit"){
                $nodelist[$v['mname']][]="updata";
            }
            if($v['aname']=="create"){
                $nodelist[$v['mname']][]="save";
            }
        }

        //将权限信息放置到session中
        Session::set('admin_user.nodelist',$nodelist);

         // var_dump($_SESSION['admin_user']['nodelist']); die;

        // 跳转到列表页
        if ($res) {
            $this->success('登陆成功',url('admin/Index/index'));
        }
    }

    public function register()
    {
        return view('index/registration',[
            'title'=>'Registration'
        ]);
    }


     public function doRegister(Request $request)
    {
         // 新增数据
        $data = $request->post();
        $data =array_diff_key($data,['repass'=>'repass']);
        $data['userpass'] = md5($data['userpass']);
        $data['name'] = '用户';

        $result = db('admin_user')->insert($data);

        if ($result) {
            $this->success('添加完成','admin/Log/login');
        } else {
            $this->error('添加失败');
        }
    }

    public function logout()
    {   
        Session::delete('admin_user');
        $this->redirect('admin/Log/login');
    }


}
